﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Petra.Gis
{

  public class CustomComponent
  {


    /// <summary>
    /// assembly name
    /// </summary>
    public string AssemblyName
    { get; set; }




    /// <summary>
    /// object class name
    /// </summary>
    public string ClassName
    { get; set; }




    /// <summary>
    /// assembly file location
    /// </summary>
    public string AssemblyFile
    { get; set; }






    /// <summary>
    /// create custom component instance using parameterless ctor
    /// </summary>
    /// <returns>new instance of custom object</returns>
    public Object CreateInstance()
    {
      try
      {
        if (AssemblyName != "" && ClassName != "")
        {
          Assembly assembly = Assembly.Load(AssemblyName);
          return assembly.CreateInstance(ClassName);
        }
        else if (AssemblyFile != "" && ClassName != "")
        {
          Assembly assembly = Assembly.LoadFile(AssemblyFile);
          return assembly.CreateInstance(ClassName);
        }
        else
          return null;
      }
      catch(Exception e){return null;}
    }






    /// <summary>
    /// create custom component instance using ctor with params
    /// </summary>
    /// <param name="ctorParams">constructor parameters</param>
    /// <returns>new instance of custom object</returns>
    public Object CreateInstance(object[] ctorParams)
    {
      try
      {
        if (AssemblyName != "" && ClassName != "")
        {
          Assembly assembly = Assembly.Load(AssemblyName);
          return assembly.CreateInstance(ClassName);
        }
        else if (AssemblyFile != "" && ClassName != "")
        {
          Assembly assembly = Assembly.LoadFile(AssemblyFile);
          return assembly.CreateInstance(ClassName, false,
            BindingFlags.CreateInstance, null, ctorParams, null, null);
        }
        else
          return null;
      }
      catch (Exception e) { return null; }
    }





    //public static T CreateObject<T>(string assemblyName, string className)
    //{
    //  Assembly assembly = Assembly.Load(assemblyName);
    //  return (T)assembly.CreateInstance(className);
    //}

  }
}
